<?php
/**
 * 工单催款申请
 * User: Administrator
 * Date: 2018/8/6/006
 * Time: 20:18
 */

namespace app\lib\Order\OrderOption;


use app\lib\Order\IsOrder\IsOrder;
use app\lib\Order\OrderInfo\GetOrderMoney;
use app\lib\Order\OrderPaymentNotice\AddOrderNotice;
use app\lib\Order\OrderPaymentNotice\OrderNotice;

class OrderUrgeMoneyOption
{
    protected $orderId;
    protected $opUid;
    public function __construct($orderId,$opUid)
    {
        $this->orderId = $orderId;
        $this->opUid   = $opUid;
    }

    /**
     * 获取工单最近一期未交款数据
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function getMoneyInfo(){
        /*判断是否存在未交款记录*/
        $moneyModel  =  (new GetOrderMoney($this->orderId,false));
        $info = $moneyModel->getNoPayRecord();
        if(empty($info)){
            exception('该工单不存在未交款数据');
        }
        return $info;
    }

    /**
     * 验证
     * @return bool
     * @throws \Exception
     */
    protected function check(){
        $model =  (new IsOrder($this->orderId));
        /*判断工单是否进行中*/
        if(!$model->isExecuteOrder()){
            exception('工单状态不在进行中');
        };
        return true;
    }

    /**
     * 催款通知操作
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function save(){
        $info = $this->getMoneyInfo();
        /*是否存在未审核的*/
        if((new OrderNotice($this->orderId,$info['id']))->isNoReviewPay()){
            exception('已经有催款操作再申请，请等待申请结果!');
        };
        $noticeModel = new AddOrderNotice();
        /*写入通知申请*/
        $noticeModel->setOpUid($this->opUid)
        ->setOrderId($this->orderId)->setMoneyId($info['id'])
        ->setContent('催款操作,工单['.$info['name'].']')
        ->initiateOrderPayNotice();
        return true;
    }
}